import axios from 'axios'
import ipConfig from '../../ip-config'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken,getAppId,getAppIdSubs } from '@/utils/auth'

import bigInt from 'json-bigint'
// data 是服务器响应回来的，待处理的数据
const transBigInt = data => {
  try {
    // 尝试进行大数处理
    // 优选方案
    return bigInt.parse(data)
  } catch {
    // 大数处理失败，单纯的进行 JSON -> 对象的转换
    // 兜底的方案
    return data
  }
}
// create an axios instance
const service = axios.create({
  baseURL: ipConfig.baseIP, // url = base url + request url   process.env.VUE_APP_BASE_API
  // baseURL:'http://192.168.110.110:5002', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000, // request timeout
  transformResponse: [transBigInt]
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['TOKEN'] = getToken()
    }
    config.headers['APPID'] = getAppId()
    config.headers['APPID-SUBSYSTEMS'] = getAppIdSubs()
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code === 'notlogin') {
      Message({
        message: '登录失效',
        type: 'error',
        duration: 5 * 1000
      })
      store.dispatch('user/resetToken').then(() => {
        location.reload()
      })
    } else if (res.code === 'notauth') {
      Message({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      })
      return res
    } else {
      return res
    }
  },
  error => {
    // 检查超时 超时重连
    if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
      error.message = '请求超时'
    }
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误'
          break

        case 401:
          error.message = '请求错误'
          break

        case 403:
          error.message = '拒绝访问'
          break

        case 404:
          error.message = '请求地址出错'
          break

        case 408:
          error.message = '请求超时'
          break

        case 500:
          error.message = '服务器内部错误'
          break

        case 501:
          error.message = '服务未实现'
          break

        case 502:
          error.message = '网关错误'
          break

        case 503:
          error.message = '服务不可用'
          break

        case 504:
          error.message = '网关超时'
          break
        case 505:
          error.message = 'HTTP版本不受支持'
          break
        default:
          error.message = '请求错误'
      }
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      error.message = '连接服务器失败,服务器繁忙，请稍后再试'
    } else {
      // Something happened in setting up the request that triggered an Error
      error.message = '网络出现问题，请稍后再试'
    }
    Message.error(error.message)
    return Promise.reject(error)
  }
)

export default service
